package com.mask.im.server.netty.protocol;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mask.im.server.netty.model.IMReceiveMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

/**
 * 协议编码器：将业务对象转换为[4字节长度+JSON消息体]格式，封装为二进制WebSocket帧
 *
 * @author jian
 */

@Log4j2
public class MessageProtocolEncoder extends MessageToMessageEncoder<IMReceiveMessage> {

    @Override
    protected void encode(ChannelHandlerContext ctx, IMReceiveMessage receiveMessage, List<Object> out) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        String text = objectMapper.writeValueAsString(receiveMessage);
        String json = JSON.toJSONString(receiveMessage);
        // 验证序列化结果
        if (StringUtils.isBlank(json)) {
            log.warn("消息序列化结果为空，channelId: {}", ctx.channel().id().asShortText());
            return;
        }
        // 检查消息长度64KB限制
        if (json.length() > 65536) {
            log.warn("编码消息过长，channelId: {}, length: {}", ctx.channel().id().asShortText(), json.length());
            return;
        }
        // 创建WebSocket帧
        TextWebSocketFrame frame = new TextWebSocketFrame(json);
        out.add(frame);
        log.debug("消息编码成功，channelId: {}, action: {}", ctx.channel().id().asShortText(), receiveMessage.getAction());
    }
}